var menuTree;
var treeSetting = {	
		check: {
			enable: true
		},
		data:{
			key:{
				id : "functionId",
				name:"functionName"
			},
			simpleData:{
				enable:true,
				idKey:"functionId",
				pIdKey:"parentFuncId",
				rootPId:0
			}
		},
		callback:{
		}
};

$(function(){
	//加载功能权限树
	loadModuleTree();
	
	//初始化选中节点
	initTreeCheck();
	
});

function loadModuleTree(){
    $.ajax({
        type: 'post',
        async: false,
        url: appCtx + "system/module/loadAll.html?isHide=true",
        cache: false,
        dataType : "JSON",
        success: function (data) {
        	menuTree=$.fn.zTree.init($("#menuTree"), treeSetting, data);
        }
    });	
}

function initTreeCheck(){
	var menuIds = $.trim($("#menuIds").val());
	if(menuIds != null && menuIds != ""){
		var menuIdArray = menuIds.split(",");
		for(var i = 0; i < menuIdArray.length; i ++){
			var node = menuTree.getNodeByParam("functionId", menuIdArray[i], null);
			if (node) {
				menuTree.checkNode(node, true, false);
			}
		}
	}
}

/**
 * 保存用户
 * */
function saveRole() {
	var id = $.trim($("#id").val());
	var url = "";
	if(id != ""){
		url = appCtx + "system/role/updateRole.html";
	}else{
		url = appCtx + "system/role/saveRole.html";
	}
	
	var flag = true;
	var role_name = $.trim($("#role_name").val());
	if(role_name == ""){
		flag = false ;
		showVelidateModal('角色名不能为空!');
		return;
	}
	
	if (flag) {
		$.ajax({
			type : 'post',
			async : false,
			url : url,
			data : getParam(),
			cache : false,
			dataType : "JSON",
			success : function(data) {
				if (data.code == "0") {
					global.ajaxLoading.pop('操作成功!',false,2000);
					closeDataDialog();
					var funStr = "window.frames['" + mFrameName + "']."+ mDialogCallback;
					eval("(" + funStr + ")");
				}else if (data.code == "1") {
					showVelidateModal("操作失败,原因是已经存在相同角色名!");
					return;
				}  else {
					showVelidateModal("操作失败!");
					return;
				}
			},
			error : function(hxr, s, e) {
			}
		});
	}
}

function getParam(){
	//定义参数集合
	var param = new Array();
	
	//获取参数
	var id = $.trim($("#id").val());
	var role_name = $("#role_name").val();
	var memo = $("#memo").val();
	
	//功能菜单
	var functionIds = new Array();
	var nodes = menuTree.getCheckedNodes(true);
	for(var i = 0; i < nodes.length; i ++){
		var functionId = nodes[i].functionId;
		if(functionId != null && functionId != ""){
			functionIds.push(functionId);
		}
	}
	
	//组装参数
	if(id != ""){
		param.push({name : 'id',value : id});
	}
	if(role_name != ""){
		param.push({name : 'role_name',value : role_name});
	}
	if(memo != ""){
		param.push({name : "memo" ,value : memo});
	}
	if(functionIds.length > 0){
		param.push({name : 'menuIds',value : functionIds.join()});
	}else{
		param.push({name : 'menuIds',value : ''});
	}
	
	return param;
}
